//
//  PLSimpleChatRoom.m
//  Plankton
//
//  Created by Marc Schlichte on 26.07.08.
//  Copyright 2008 Framework Labs. All rights reserved.
//

#import "PLSimpleChatRoom.h"

#import "PLPlatform.h"
#import "PLDirectory.h"

@implementation PLSimpleChatRoom

@synthesize chatRoomAid = ownAid;

- (id)initWithPlatform:(PLPlatform *)platform_
{
    if (self = [super init]) {
        platform = [platform_ retain];
        ownAid = [[platform createAid] retain];
        members = [[NSMutableSet alloc] init];
        nicks = [[NSMutableDictionary alloc] init];
        
        pattern = [[PLPattern patternAny] retain];
        [pattern setMessageHandler:self];
        [platform receive:pattern by:ownAid];
    }
    return self;
}

- (void)dealloc
{
    [nicks release];
    [members release];
    [pattern release];
    [platform release];
    [ownAid release];
    [super dealloc];
}

- (void)handleMessage:(id)message forPattern:(PLPattern *)pattern_
{
    NSString *perf = [message objectAtIndex:0];
    if ([perf isEqual:@"join"]) {
        NSString *aid = [message objectAtIndex:1];
        [members addObject:aid];
        [nicks setObject:[message lastObject] forKey:aid];
    }
    else if ([perf isEqual:@"leave"]) {
        NSString *aid = [message objectAtIndex:1];        
        [members removeObject:aid];
        [nicks removeObjectForKey:aid];
    }
    else if ([perf isEqual:@"inform"]) {
        NSString *nick = [nicks objectForKey:[message objectAtIndex:1]];
        NSArray *reply = [NSArray arrayWithObjects:nick, [message lastObject], nil];
        [platform multicast:reply to:members];
    }   
    else if ([perf isEqual:@"changeNick"]) {
        NSString *aid = [message objectAtIndex:1];
        if ([members containsObject:aid]) {
            NSString *oldNick = [[[nicks objectForKey:aid] retain] autorelease];
            NSString *newNick = [message lastObject];
            [nicks setObject:newNick forKey:aid];
            [platform multicast:[NSArray arrayWithObjects:oldNick, 
                                [NSString stringWithFormat:@"changed nick to %@", newNick], 
                                nil] to:members];
        }
    }
    [platform receive:pattern by:ownAid];
}

@end
